package com.example.sendmessage.server.core;

import com.example.sendmessage.common.ConsumerEnv;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 队列类
 */
public class Queue {
    // 队列唯一id
    private String name;
    // 是否持久化 默认false
    private boolean durable = false;
    // 是否唯一使用
    private boolean exclusive = false;
    // 自动删除
    private boolean autoDelete = false;
    private Map<String, Object> arguments = new HashMap<>();
    private List<ConsumerEnv> consumerEnvList = new ArrayList<>();
    private AtomicInteger consumerSeq = new AtomicInteger(0);

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isDurable() {
        return durable;
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isExclusive() {
        return exclusive;
    }

    public void setExclusive(boolean exclusive) {
        this.exclusive = exclusive;
    }

    public boolean isAutoDelete() {
        return autoDelete;
    }

    public void setAutoDelete(boolean autoDelete) {
        this.autoDelete = autoDelete;
    }

    public String getArguments() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(arguments);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "{}";
    }

    public void setArguments(String argumentsJson) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            this.arguments = objectMapper.readValue(argumentsJson, new TypeReference<Map<String, Object>>() {});
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    public void setArguments(Map<String, Object> arguments) {
        this.arguments = arguments;
    }

    public ConsumerEnv chooseConsumer() {
        if (consumerEnvList.size() == 0) {
            // 当前队列还未被订阅
            return null;
        }
        // 记录消费者轮询的位置
        int index = consumerSeq.get() %  consumerEnvList.size();
        // 需要将消费者的序号加1，确保下次轮询到下一个消费者
        consumerSeq.getAndIncrement();
        return consumerEnvList.get(index);
    }

    public void addConsumer(ConsumerEnv consumerEnv) {
        consumerEnvList.add(consumerEnv);
    }

    // 测试接口
    public Object getArguments(String key) {
        return arguments.get(key);
    }

    public void setArguments(String key, Object value) {
        arguments.put(key, value);
    }
}
